package example

import (
	"context"
	"errors"
	"gitee.com/alex_li/uhf"
	"gitee.com/alex_li/uhf/e310"
	"gitee.com/alex_li/uhf/serial"
	"gitee.com/alex_li/uhf/stream"
	"github.com/lishimeng/go-log"
	sfinder "github.com/lishimeng/serial-finder"
)

var (
	BaudRate = 115200
)

func NewE310Serial(ctx context.Context, onConnect func(sdk uhf.Sdk)) (err error) {
	finder := sfinder.New(sfinder.CP2x)
	list, err := finder.Find()
	if err != nil {
		log.Info(err)
		return
	}
	if len(list) == 0 {
		log.Info(errors.New("no serial port"))
		return
	}
	uart := list[0]
	log.Info("uart: %s", uart.Name)
	port := serial.New(serial.Config{Name: uart.Name, Baud: BaudRate})
	err = port.Connect()
	if err != nil {
		log.Info(err)
		return
	}
	defer func() {
		_ = port.Close()
	}()
	io := stream.New(ctx, port.Ser)
	sdk := e310.New(ctx, io)
	if onConnect != nil {
		onConnect(sdk)
	}

	return
}
